import React, { useMemo } from 'react';
import './Calendar.css';
import { ConfigProvider, Flex, Select } from 'antd';
import { createStyles } from 'antd-style';
import dayjs from 'dayjs';
import { useTheme } from '@/store/settingsStore.ts';
import { ThemeMode, style } from '@ycx/ui';

const useStyle = createStyles(({ css }) => {
  const gridLayout = css`
    display: grid;
    grid-template-columns: repeat(7, 1fr);
  `;

  return {
    select: css`
      width: 80px;

      & .ant-select-selector {
        border-radius: 14px !important;
      }
    `,
    calendarWrapper: css`
      display: flex;
      flex-direction: column;
      border-radius: 12px;
      background: var(--ycx-card-bg-color);
      user-select: none;
    `,
    header: css`
      display: flex;
      align-items: center;
      width: 100%;
      gap: 12px;
      padding: 12px 8px;
      border-bottom: 0.5px solid var(--ycx-divider-color);
      justify-content: space-around;

      & > div {
        cursor: pointer;
      }
    `,

    dateWrapper: css`
      padding: 8px;
    `,
    weekDays: css`
      ${gridLayout};
      text-align: center;
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 20px; /* 166.667% */
      color: var(--ycx-font-color-l1);

      & > div {
        padding: 5px 0;
        //outline: 1px solid;
      }
    `,
    days: css`
      ${gridLayout};
    `,
    day: css`
      text-align: center;
      padding: 2px 0;
      cursor: pointer;
      border-radius: 12px;
      color: var(--ycx-font-color-l1);
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 20px; /* 166.667% */

      &:hover {
        background: rgba(76, 104, 255, 0.08);
      }

      &.other-month {
        color: var(--ycx-font-color-l4);
      }

      &.today {
        outline: 1px solid var(--ycx-primary-color);
      }
    `,
  };
});

const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

interface CalendarProps {
  onDateSelect: (date: dayjs.Dayjs) => void;
  currentDate: dayjs.Dayjs;
}

const Calendar: React.FC<CalendarProps> = ({ currentDate, onDateSelect }) => {
  const theme = useTheme();
  const color = useMemo(() => {
    return theme === ThemeMode.Light
      ? style.fontColorLevelThreeLight
      : style.fontColorLevelThreeDark;
  }, [theme]);

  const DoubleLeft = () => {
    return (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="10"
        height="10"
        viewBox="0 0 10 10"
        fill="none"
      >
        <path d="M5 9L1 5L5 1" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
        <path d="M9 9L5 5L9 1" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };

  const Left = () => {
    return (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="16"
        height="16"
        viewBox="0 0 16 16"
        fill="none"
      >
        <path d="M10 4L6 8L10 12" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };

  const Right = () => {
    return (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="16"
        height="16"
        viewBox="0 0 16 16"
        fill="none"
      >
        <path d="M6 12L10 8L6 4" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };

  const DoubleRight = () => {
    return (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="10"
        height="10"
        viewBox="0 0 10 10"
        fill="none"
      >
        <path d="M5 9L9 5L5 1" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
        <path d="M1 9L5 5L1 1" stroke={color} strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };

  const { styles } = useStyle();
  // const [currentDate, setCurrentDate] = useState(dayjs());

  const getDaysInMonth = (date: dayjs.Dayjs) => {
    const year = date.year();
    const month = date.month();
    const daysInMonth = date.daysInMonth();
    const firstDayOfMonth = date.startOf('month').day();

    const days: dayjs.Dayjs[] = [];
    for (let i = 0; i < firstDayOfMonth; i++) {
      days.push(date.startOf('month').subtract(firstDayOfMonth - i, 'day'));
    }
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(dayjs(new Date(year, month, i)));
    }
    const remainingDays = 42 - days.length;
    for (let i = 1; i <= remainingDays; i++) {
      days.push(date.endOf('month').add(i, 'day'));
    }
    return days;
  };

  const changeMonth = (delta: number) => {
    // setCurrentDate(currentDate.add(delta, 'month'));
    onDateSelect(currentDate.add(delta, 'month'));
  };

  const handleYearChange = (year: number) => {
    // setCurrentDate(currentDate.year(year));
    onDateSelect(currentDate.year(year));
  };

  const handleMonthChange = (month: number) => {
    // setCurrentDate(currentDate.month(month));
    onDateSelect(currentDate.month(month));
  };

  const isActive = (date: dayjs.Dayjs) => {
    return date.isSame(currentDate, 'day');
  };

  const isOtherMonth = (date: dayjs.Dayjs) => {
    return date.month() !== currentDate.month();
  };

  const handleClickDay = (date: dayjs.Dayjs) => {
    // const cd = currentDate.set('date', date);
    // setCurrentDate(date)
    onDateSelect(date);
    if (onDateSelect) onDateSelect(date);
  };

  return (
    <div className={styles.calendarWrapper}>
      <div className={styles.header}>
        <Flex gap={8} align="center">
          <div onClick={() => changeMonth(-12)}>
            <DoubleLeft />
          </div>
          <div onClick={() => changeMonth(-1)}>
            <Left />
          </div>
        </Flex>
        <Flex gap={8}>
          <ConfigProvider
            theme={{
              components: {
                Select: {
                  fontSize: 12,
                },
              },
            }}
          >
            <Select
              size="small"
              className={styles.select}
              style={{ width: '80px' }}
              value={currentDate.year()}
              options={Array.from({ length: 10 }, (_, i) => currentDate.year() - 5 + i).map(
                (year) => ({
                  label: year,
                  value: year,
                }),
              )}
              onChange={handleYearChange}
            />
            <Select
              size="small"
              className={styles.select}
              style={{ width: '70px' }}
              value={currentDate.month()}
              options={Array.from({ length: 12 }, (_, i) => ({ label: `${i + 1}月`, value: i }))}
              onChange={handleMonthChange}
            />
          </ConfigProvider>
        </Flex>
        <Flex gap={8} align="center">
          <div onClick={() => changeMonth(1)}>
            <Right />
          </div>
          <div onClick={() => changeMonth(12)}>
            <DoubleRight />
          </div>
        </Flex>
      </div>
      <div className={styles.dateWrapper}>
        <div className={styles.weekDays}>
          {weekDays.map((day) => (
            <div key={day}>{day}</div>
          ))}
        </div>
        <div className={styles.days}>
          {getDaysInMonth(currentDate).map((date, index) => (
            <div
              key={index}
              className={`${styles.day} ${isActive(date) ? 'today' : ''} ${isOtherMonth(date) ? 'other-month' : ''}`}
              onClick={() => handleClickDay(date)}
            >
              {date.date()}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Calendar;
